<?php

namespace User\Controller;
use Think\Controller\RestController;
use Common\Controller\PrettyRestController;
use User\Model\UserModel;

class AuthController extends PrettyRestController {
    
    /* get => login
     * post => signup
     * delete => logout
    **/
    protected $allowMethod = array('get', 'put', 'post', 'delete');
    protected $allowType = array('json');
    
    protected $token = 0;
    protected $userId = 0;
    protected $userName = '';
    protected $userEmail = '';
    protected $userPhone = '';
    protected $userPassword = '';

    protected $status = 200;
    protected $msg = 'OK';
    protected $data = array();

    protected $userModel = null;

    public function __construct() {
        
        parent::__construct();

        if (is_null($this->userModel)) {
            // TODO try D('user')?
            $this->userModel = new UserModel();  
        }
    }

    public function auth() {
        
        switch ($this->_method) {
            case 'get':
                $this->token = I('get.token', '');
                $this->userId = I('get.uid', 0);
                $this->userName = I('get.username', '');
                $this->userPassword = I('get.userpassword', '');
                
                // if session already exist
                if ($this->token != '' && $this->uid != 0) {
                    if ($this->userModel->validateToken($this->userId, $this->token)) {
                        session('uid', $this->uid);        
                        $this->token = $this->genToken($uid);
                        $this->updateSession();

                        $result = $this->getUserById($uid);
                        $this->userName = $result['username'];
                        $this->userEmail = $result['email'];
                        $this->userPhone = $result['phone'];

                        $this->status = 200;
                        $this->msg = "user recover";
                        $this->prettyResponse($this->status, $this->msg);
                    } else {
                        $this->status = 401;
                        $this->msg = "invalid token";
                        $this->prettyResponse($this->status, $this->msg);
                    }
                } else {
                    $result = $this->userModel->login($this->userName, $this->userPassword);
                    if (is_array($result)) {
                        // password ok
                        $this->userId = $result['uid'];
                        $this->userName = $result['username'];
                        $this->userEmail = $result['email'];
                        $this->userPhone = $result['phone'];
                        $this->token = $this->userModel->genToken($this->userId);
                        
                        session('uid', $this->uid);
                        $this->updateSession();
                        
                        $this->status = 200;
                        $this->msg = "login success";
                        $this->data['token'] = $this->token;
                        $this->data['uid'] = $this->userId;
                        $this->data['userphone'] = $this->userPhone;
                        $this->data['useremail'] = $this->userEmail;

                        $this->prettyResponse($this->status, $this->msg, $this->data);
                    } elseif (is_null($result)) {
                        // user not found
                        $this->status = 404;
                        $this->msg = "User Not Found";
                        $this->prettyResponse($this->status, $this->msg);
                    } else {
                        // password error
                        $this->status = 401;
                        $this->msg = "password error";
                        $this->prettyResponse($this->status, $this->msg);
                    }
                }
                break;

            case 'post':
                $this->token = I('post.token', '');
                $this->userId = I('post.uid', 0);
                $this->userName = I('post.username', '');
                $this->userEmail = I('post.useremail', '');
                $this->userPhone = I('post.userphone', '');
                $this->userPassword = I('post.userpassword', '');

                // if session already exist
                if ($this->token != '' or $this->uid != 0) {
                    $this->status = 400;
                    $this->msg = "Session already started";
                    $this->prettyResponse($this->status, $this->msg);
                }

                // check UserName format
                if (!$this->checkNameFormat()) {
                    $this->status = 400;
                    $this->msg = "userName format is invalid";
                    $this->prettyResponse($this->status, $this->msg);
                }
                
                // check User Email format
                if (!$this->checkEmailFormat()) {
                    $this->status = 400;
                    $this->msg = "userEmail format is invalid";
                    $this->prettyResponse($this->status, $this->msg);
                }

                // check User Phonenumber format
                if (!$this->checkPhoneFormat()) {
                    $this->status = 400;
                    $this->msg = "userPhone Number format is invalid";
                    $this->prettyResponse($this->status, $this->msg);
                }

                // check if user already exist
                if ($this->userModel->checkUserByName($this->userName)) {
                    $this->status = 400;
                    $this->msg = "username already exist";
                    $this->prettyResponse($this->status, $this->msg);
                }

                // check if email already exist
                if ($this->userModel->checkUserByEmail($this->userEmail)) {
                    $this->status = 400;
                    $this->msg = "user Email already exist";
                    $this->prettyResponse($this->status, $this->msg);
                }

                // check if phone already exist
                if ($this->userModel->checkUserByPhone($this->userPhone)) {
                    $this->status = 400;
                    $this->msg = "user Phone number already exist";
                    $this->prettyResponse($this->status, $this->msg);
                }

                // TODO
                // Generate and validate SMS code 

                // Now userinfo is ready, try to register 
                if (!$this->userModel->register(
                    $this->userName,
                    $this->userEmail,
                    $this->userPhone,
                    $this->userPassword )) {

                    // Server internal error 
                    $this->status = 500;
                    $this->msg = "Server Internal Error, Please try later";
                    $this->prettyResponse($this->status, $this->msg);
                } else {
                    // Register ok, hint user to login
                    $this->status = 200;
                    $this->msg = "Register ok, then go login";
                    $this->prettyResponse($this->status, $this->msg);
                }
                break;

            case 'delete':
                // TODO
                $this->prettyResponse(400, 'this is delete method');
                break;
        }
    }

    protected function checkNameFormat() {
        // TODO 
        return true;
    }

    protected function checkEmailFormat() {
        // TODO 
        return true;
    }

    protected function checkPhoneFormat() {
        // TODO 
        return true;
    }

    protected function checkPasswordFormat() {
        // TODO 
        return true;
    }

    protected function checkSMSCode() {

    }

    public function updateSession() {
        session('username', $this->userName);
        session('useremail', $this->userEmail);
        session('userphone', $this->userPhone);
        session('token', $this->token);
    }

    public function __destruct() {
        if (!is_null($this->userModel)) {
            $this->userModel = null;
        }
    }
}
